import { DownOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Dropdown, Menu, Popconfirm } from 'antd';
import md5 from 'blueimp-md5';
import React, { useRef, useState } from 'react';
import { Link, useModel } from 'umi';
import AuthForm from './components/AuthForm';
import ChangePasswordForm from './components/ChangePasswordForm';

import * as c from '@/services/consts';
import * as api from '@/services/user';
import * as utils from '@/utils/utils';
import { PageContainer } from '@ant-design/pro-components';

const getLoginInfo = (user: API.UserModel) => {
  let info = '';
  if (user.loginCountry == '中国') {
    info += `${user.loginCountry ?? ''} ${user.loginProvince ?? ''} ${
      user.loginCity ?? ''
    }`;
    if (
      user.loginNet &&
      user.loginNet != '' &&
      user.loginNet.indexOf('内网') == -1
    ) {
      info += ` [${user.loginNet}]`;
    }
  } else {
    info = user.loginCountry ?? '';
  }

  return info;
};

const UserList: React.FC = () => {
  const [productId, setProductId] = useState<string | undefined>(undefined);
  const [username, setUsername] = useState<string>('');
  const [current, setCurrent] = useState<API.UserModel | undefined>(undefined);
  const [pwdFormVisible, setPwdFormVisible] = useState<boolean>(false);
  const [authFormVisible, setAuthFormVisible] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();

  const { hasRight } = useModel('useAuthModel');
  const { initialState } = useModel('@@initialState');

  const { getProduct, getProductMenuItems } = useModel(
    'useGlobalModel',
    (model) => ({
      getProduct: model.getProduct,
      getProductMenuItems: model.getProductMenuItems,
    }),
  );

  const productMenuItems = getProductMenuItems(true);

  const handlePwdFormSubmit = async (record: API.User) => {
    // console.log(record);

    let result: API.Result;
    if (record.password && record.password !== '') {
      record.password = md5(record.password).toLowerCase();
    }
    if (current) {
      result = await api.changePassword({
        ...current,
        ...record,
      });
    } else {
      result = { success: true };
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setPwdFormVisible(false);
    }
  };

  const handleAuthFormSubmit = async (record: API.UserAuthModel) => {
    //console.log(record);

    let result: API.Result;
    if (current) {
      result = await api.auth({
        userId: current.id,
        serviceSetId: record.serviceSetId,
      });
    } else {
      result = { success: true };
    }

    if (result && result.success === true) {
      setCurrent(undefined);
      setAuthFormVisible(false);

      actionRef.current?.reload();
    }
  };

  const handleRemove = async (id: string) => {
    const result = await api.remove({ key: id });
    if (result.success) {
      actionRef.current?.reload();
    }
  };

  const loadData = async (
    params: { [key: string]: any },
    sorter?: { [key: string]: any },
    filter?: { [key: string]: any },
  ) => {
    const result = await api.list(params, sorter, filter);
    return Promise.resolve(result);
  };

  let columns: ProColumns<API.UserModel>[] = [
    {
      title: '状态',
      align: 'center',
      width: 80,
      dataIndex: 'status',
      sorter: true,
      search: false,
      valueEnum: {
        true: { status: 'Success', text: '' },
        false: { status: 'Error', text: '' },
      },
    },
    {
      title: '产品',
      align: 'center',
      width: 100,
      dataIndex: 'productId',
      sorter: true,
      search: false,
      renderText: (_, record) => {
        if (record.productId) {
          const product = getProduct(record.productId);
          if (product) {
            return product.name;
          }
        }
        return '';
      },
    },
    {
      title: '用户名',
      dataIndex: 'username',
      sorter: true,
    },
    // {
    //   title: 'Key',
    //   dataIndex: 'accountKey',
    //   sorter: true,
    // },
    {
      title: '服务类型',
      // align: 'center',
      width: 120,
      search: false,
      renderText: (_, record) => {
        let text = '';
        if (record.serviceType) {
          text += `[${c.getMemberLevelText(record.serviceType.memberLevel)}]`;
        }
        if (record?.serviceType?.name) {
          text += record?.serviceType?.name;
        }

        return text;
      },
    },
    {
      title: '到期时间',
      align: 'center',
      search: false,
      render: (_, record) => {
        if (!record.serviceType) {
          return null;
        }
        if (record.serviceType.expireDays < 1) {
          return (
            // <Tag color="error" key={record.serviceType.id}>
            //   {utils.formatUtcToLocal(record.serviceType.expireTime)}
            // </Tag>
            <span style={{ color: '#ff4d4f' }}>
              {utils.formatUtcToLocal(record.serviceType.expireTime)}
            </span>
          );
        } else if (
          record.serviceType.expireDays >= 1 &&
          record.serviceType.expireDays <= 7
        ) {
          return (
            // <Tag color="warning" key={record.serviceType.id}>
            //   {utils.formatUtcToLocal(record.serviceType.expireTime)}
            // </Tag>
            <span style={{ color: '#faad14' }}>
              {utils.formatUtcToLocal(record.serviceType.expireTime)}
            </span>
          );
        } else {
          return (
            <>
              <span style={{ color: '' }}>
                {utils.formatUtcToLocal(record.serviceType.expireTime)}
              </span>
            </>
          );
        }
      },
    },
    {
      title: '平台',
      // align: 'center',
      width: 130,
      dataIndex: 'platform',
      sorter: true,
      search: false,
    },
    {
      title: '版本',
      align: 'center',
      width: 60,
      dataIndex: 'ver',
      sorter: true,
      search: false,
    },
    {
      title: '时区',
      align: 'center',
      width: 80,
      dataIndex: 'timezone',
      sorter: true,
      search: false,
    },
    {
      title: '语言',
      align: 'center',
      width: 80,
      dataIndex: 'lang',
      sorter: true,
      search: false,
    },
    {
      title: '渠道',
      // align: 'center',
      width: 100,
      dataIndex: 'channel',
      sorter: true,
      search: false,
    },
    {
      title: '指定地区',
      align: 'center',
      width: 120,
      dataIndex: 'userArea',
      sorter: true,
      search: false,
    },
    {
      title: '登录时间',
      align: 'center',
      dataIndex: 'loginTime',
      sorter: true,
      search: false,
      renderText: (_, record) => {
        return utils.formatUtcToLocal(record.loginTime);
      },
    },
    {
      title: '登录IP',
      align: 'center',
      width: 120,
      dataIndex: 'loginIp',
      sorter: true,
      search: false,
    },
    {
      title: '登录信息',
      search: false,
      render: (_, record) => {
        return (
          <>
            <span>{getLoginInfo(record)}</span>
          </>
        );
      },
    },
    {
      title: '注册',
      width: 80,
      align: 'center',
      dataIndex: 'registMode',
      sorter: true,
      search: false,
      renderText: (val) => {
        const type = c.getRegistModeText(val);
        return type;
      },
    },
    {
      title: '注册时间',
      align: 'center',
      dataIndex: 'createTime',
      sorter: true,
      search: false,
      renderText: (_, record) => {
        return utils.formatUtcToLocal(record.createTime);
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      ellipsis: true,
      search: false,
    },
    {
      title: '设备ID',
      dataIndex: 'loginDeviceid',
      hideInTable: true,
    },
    {
      title: 'Key',
      dataIndex: 'accountKey',
      hideInTable: true,
    },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 200,
      render: (_, record) => {
        let cmps = [];
        if (hasRight('user_update')) {
          cmps.push(
            <Link key="update" to={`/customer/user/update/${record.id}`}>
              编辑
            </Link>,
          );
        }
        if (
          hasRight('user_auth') &&
          record.registMode.toString() != c.RegistMode.Auto.value
        ) {
          cmps.push(
            <a
              key="auth"
              onClick={(e) => {
                setCurrent(record);
                setAuthFormVisible(true);
              }}
            >
              授权
            </a>,
          );
        }
        if (initialState?.currentUser?.username == 'husq') {
          cmps.push(
            <Popconfirm
              key="delete"
              title="确定要删除吗?"
              onConfirm={async () => {
                await handleRemove(record.id);
              }}
            >
              <a>删除</a>
            </Popconfirm>,
          );
        }
        if (
          hasRight('user_changepassword') &&
          record.registMode.toString() == c.RegistMode.Manual.value
        ) {
          cmps.push(
            <Dropdown
              key="dd"
              overlay={
                <Menu key="moreAtcions">
                  {hasRight('user_changepassword') &&
                    record.registMode.toString() ==
                      c.RegistMode.Manual.value && (
                      <Menu.Item key="0">
                        <a
                          key="changepassword"
                          onClick={(e) => {
                            setCurrent(record);
                            setPwdFormVisible(true);
                          }}
                        >
                          修改密码
                        </a>
                      </Menu.Item>
                    )}
                </Menu>
              }
            >
              <a
                className="ant-dropdown-link"
                onClick={(e) => e.preventDefault()}
              >
                更多 <DownOutlined />
              </a>
            </Dropdown>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        columnEmptyText={''}
        actionRef={actionRef}
        columns={columns}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: productId,
            items: productMenuItems,
            onChange: (tabKey) => {
              setProductId(tabKey as string);
            },
          },
          // search: {
          //   onSearch: (value: string) => {
          //     setUsername(value);
          //   },
          //   style: { width: 400 },
          // },
        }}
        toolBarRender={() => {
          return [];
        }}
        pagination={{
          defaultPageSize: 15,
          pageSizeOptions: ['15', '30', '60', '100'],
          hideOnSinglePage: true,
          // current: pageCurrent,
          // total: totalCount,
        }}
        params={{
          productId:
            productId && productId !== c.DefaultOptionAll.key
              ? parseInt(productId)
              : undefined,
        }}
        request={loadData}
      />
      <AuthForm
        visible={authFormVisible}
        current={current}
        onSubmit={handleAuthFormSubmit}
        onCancel={() => {
          setCurrent(undefined);
          setAuthFormVisible(false);
        }}
      />
      <ChangePasswordForm
        visible={pwdFormVisible}
        current={current}
        onSubmit={handlePwdFormSubmit}
        onCancel={() => {
          setPwdFormVisible(false);
          setCurrent(undefined);
        }}
      />
    </PageContainer>
  );
};

export default UserList;
